<?php
/**
 * Created by PhpStorm.
 * User: xeng
 * Date: 2018/2/5
 * Time: 11:22
 */

/*
 * 银行记录
 */
namespace Home\Controller;
use Think\Controller;
use Think\Model;

class BankrecoredController extends AuthController {
    /*
     * 默认展示银行记录
     */
    protected $con ='DB_CONFIG1';

    public function index(){
        $this->CheckPower('3003');
        $this->display('');
    }

    public function exchange(){
        $this->CheckPower('1301');
        $this->display('');
    }
    public function exchange_pass(){
        if(!empty($_GET['id'])){
            if(IS_GET){
                $useraccount = M('','',$this->con);
                $gameid = $_GET['id'];
                $d['text'] = $_GET['text'];
                $d['handlename'] = $_SESSION['ltq_game_admin_user']['name'];
                $d['handletime'] = date('Y-m-d H:i:s',time());
                $d['status'] = $_GET['status'];
                $s = $useraccount->table('data_excharge')->where('id='.$gameid)->save($d);
                $da = $useraccount->table('data_excharge')->where('id='.$gameid)->find();
                $data['code'] = 10;
                $data['msg'] ='操作失败';
                if($s){
                    $serverID = C('DATA_HOST');
                    $price = (double)$da['price'];
                    $gameid = intval($da['gameid']);
                    $status =intval($da['status']);
                    $channel = intval($da['channel']);
                    //准备数组
                    $command=array(
                        'gameid'=>$gameid,
                        'status'=>$status,
                        'price'=>$price,
                        'channel'=>$channel,
                    );
                    $command = json_encode($command);
                    $rpcname="excharge";
                    $time=date("Y-m-d H:i:s",time());
                    $add['ServerIPAddr'] =$serverID;
                    $add['Command'] =$command;
                    $add['RpcName'] =$rpcname;
                    $add['Time'] =$time;
                    $commands = M('','','DB_CONFIG1');
                    $re = $commands->table('data_command')->add($add);
                    if($status == 1 && $channel=='2'){
                       $num = $this->payment($da['id']);
                       $data['code'] = 0;
                       switch ($num){
                           case 3:
                               $d['status'] = 4;
                               $s = $useraccount->table('data_excharge')->where('id='.$gameid)->save($d);
                               $data['msg'] ='提现异常';
                               break;
                           case 1:
                               $data['code'] = 1;
                               $data['msg'] ='操作成功';
                               break;
                           case 5:
                               $d['status'] = 4;
                               $s = $useraccount->table('data_excharge')->where('id='.$gameid)->save($d);
                               $data['code'] = 0;
                               $data['msg'] ='提现异常';
                               break;
                       }
                    }else{
                        $data['code'] = 1;
                        $data['msg']  = '操作成功';
                    }

                }
                $this->ajaxReturn($data);
            }
        }
        $this->CheckPower('1303');
        $this->assign("status",'1');
        $this->display('change_pass');
    }

    public function returns(){
        $useraccount = M('','',$this->con);
        $gameid = $_GET['id'];
        $d['status'] = 0;
        $s = $useraccount->table('data_excharge')->where('id='.$gameid)->save($d);
        $ddd = $useraccount->table('data_excharge')->fetchSql(true)->where('id='.$gameid)->save($d);
        $data['code'] = 0;
        $data['msg']  = $ddd;
        if($s){
            $data['code'] = 1;
            $data['msg']  = $ddd;
        }
        $this->ajaxReturn($data);
    }

    public function exchange_no(){
        $this->CheckPower('1304');
        $this->assign("status",'3');
        $this->display('change_pass');
    }
    //银行代付自动提现
    public function payment($gameid=0){
        if($gameid == 0){
            $gameid = $_GET['id'];
        }
        $useraccount = M('','',$this->con);
        $data = $useraccount->table('data_excharge')->where('id='.$gameid.' and (status = \'1\' or status = \'4\')')->find();
        if(!empty($data)){
            $price = intval($data['price'])*100;
            $native = array(
                "cpTradeNo" =>intval($data['id']) ,
                "cpId" => '1557815148481',
                "withdrawAmount" => intval($price),
                'payeeAccount'=>$data['exaccount'],
                "bankCode" => intval($data['bankcode']),
                "notifyUrl" => 'http://'.$_SERVER['HTTP_HOST'].'/Bankrecored/notifyUrl'
            );
            $md5str = "";
            foreach ($native as $key => $val) {
                $md5str = $md5str . $key . "=" . $val . "|";
            }
            $sign = md5($md5str . "key=C2A3E8F246C2E826907");
            $native['sign'] = $sign;
            $native['payeeName'] = $data['name'];
            $native['bankBranchName'] = $data['banksubbranch'];
            $native['bankProvince'] = $data['bankprovince'];
            $native['bankCity'] = $data['bankcity'];
            S(array('type'=>'file','prefix'=>'payment','expire'=>60*60*24));
            $url = 'http://154.209.8.8:8080/payee/withdraw.do';
            $order_res = $this->http_post_data($url, $native);
            S('paysss',$order_res);
            S('jianming',$native);
            $code = $order_res['status'];
            if($code == 200) {
                $d['number'] = $order_res['number'];
                $d['status'] = '2';
                $s = $useraccount->table('data_excharge')->where('id='.$gameid)->save($d);
                if($s){
                    if(empty($_GET['id'])){
                        return 1;
                    }else{
                        $dre['code'] = 1;
                        $dre['msg']  = $native;
                        $this->ajaxReturn($dre);
                    }
                }
            }else{
                if(empty($_GET['id'])){
                    return 3;
                }else{
                    $d['number'] =$order_res['statusDes'];
                    $d['status'] = '4';
                    $s = $useraccount->table('data_excharge')->where('id='.$gameid)->save($d);
                    $dre['code'] = 111;
                   // $dre['wod'] = $md5str . "key=C2A3E8F246C2E826907";
                    $dre['msg']  = '操作失败';
                    $this->ajaxReturn($dre);
                }
            }
        }else{
            if(empty($_GET['id'])){
                return 3;
            }else{
                $dre['code'] = 9;
                $dre['msg']  ='订单查询失败';
                $this->ajaxReturn($dre);
            }
        }
    }
    function http_post_data($url, $params) {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        // curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));
        /* curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));*/
        ob_start();
        curl_exec($curl);
        curl_close($curl);
        $contents = ob_get_contents();
        ob_end_clean();
        return json_decode($contents, true);
    }
    public function paynotifyUrl(){
            S(array('type'=>'file','prefix'=>'payment','expire'=>60*60*24));
            S("sdfsd",'通知已进入');
            // 订单异步通知数据
            $orderAsyncNotified = $_POST;
            S('Jpay',$orderAsyncNotified);
            if ($orderAsyncNotified === null) {
                exit('返回参数没有获取到');
            }
            //000000086400a:8:{s:9:"cpOrderId";s:18:"Jpay20190515100403";s:4:"cpId";s:13:"1557815148481";s:5:"price";s:3:"100";s:7:"orderId";s:20:"20190515100756752427";s:7:"payTime";s:28:"Wed May 15 10:19:32 CST 2019";s:6:"status";s:3:"200";s:9:"statusDes";s:10:"paySuccess";s:4:"sign";s:32:"4897f7eb8b07a8f98ed6b1c197e7bd98";}
            if($this->params['cpId']==$orderAsyncNotified['cpId']){
                if($orderAsyncNotified['status'] == 200){
                    $commands = M('','','DB_CONFIG1');
                    $save['status'] = 2;
                    $update = $commands->table('data_excharge')->where("id='".$orderAsyncNotified['cpTradeNo']."'")->save($save);
                    if(!$update){
                        S('sdfdfsssd','订单更新失败');
                        exit('失败');
                    }else{
                        exit('OK');
                    }
                }
            }else {
                exit('返回参数没有获取到');
            }
    }

    //兑换审核列表
    public function getexchange(){
        $useraccount = M('','',$this->con);
        $url = pageurl(__SELF__);
        $pagesize = empty($url['limit'])?10:$url['limit'];
        $page = empty($url['page'])?1:$url['page'];
        $state = ($page-1)*$pagesize;
        if(!empty($url['channel']) || $url['channel']=='0'){
            $where['channel'] = array('eq',$url['channel']);
        }else{
            $where['channel'] = array('in','0,1,2');
        }
        if(!empty($url['tradetype'])){
            if($url['tradetype']==1){
                $where['status'] = array('in','1,2,4');
            }else{
                $where['status'] = array('eq',$url['tradetype']);
            }

        }else{
            $where['status'] = array('eq','0');
        }
        if(!empty($url['startime']) && !empty($url['endtime'])){
            $where['time'] = array('between',array($url['startime'],$url['endtime']));
        }
        if($url['gameid'] > 0 && !empty($url['gameid'])){
            $where['gameid'] = array('eq',$url['gameid']);
        }

        $count=$useraccount->table('data_excharge')->where($where)->count();
       // $s=$useraccount->table('data_excharge')->fetchSql(true)->where($where)->count();
        $sumprice=$useraccount->table('data_excharge')->field('sum(price) as sumprice')->where($where)->find();
        $sql=$useraccount->table('data_excharge')->fetchSql(true)->field('sum(price) as sumprice')->where($where)->find();

        $list = $useraccount->table('data_excharge')->where($where)->order('handletime desc')->limit($state,$pagesize)->select();

        foreach ($list as $key => $value) {
            if($value['channel'] == '0'){
                $list[$key]["channelname"] = '支付宝';
            }elseif ($value['channel'] == '1'){

                $list[$key]["channelname"] = '微信';
            }else if($value['channel'] == '3'){
                $list[$key]["channelname"] = '代理充值';
            }else{
                $list[$key]["channelname"] = '银行卡';
            }
            $list[$key]['charge'] = $value['price']/0.98*0.02;
            //$list[$key]['price'] =$value['price'] - $value['price'] * 0.02;
        }
       // $list[0]["sumprice"] = empty($sumprice['sumprice'])?0:$sumprice['sumprice'];
        $r=$this->actionLog((int)(1),'查询了','兑换审核信息');
        $data['code'] = 0;
        $data['message'] = '';
        $data['where'] = $where;
        $data['sql'] = $sql;
        $data['count'] = $count;
        $data['data'] = $list;
        $data['sumprice'] = empty($sumprice['sumprice'])?0:$sumprice['sumprice'];
        $this->ajaxReturn($data,'json');
    }




    public function getnotice(){
        $useraccount = M('','',$this->con);
        $url = pageurl(__SELF__);
        $pagesize = empty($url['limit'])?10:$url['limit'];
        $page = empty($url['page'])?1:$url['page'];
        $state = ($page-1)*$pagesize;
        $count=$useraccount->table('cfg_notice')->count();
        $list = $useraccount->table('cfg_notice')->order('sort asc')->limit($state,$pagesize)->select();


        $r=$this->actionLog((int)(1),'查询了','游戏公告');
        $data['code'] = 0;
        $data['message'] = '';
        $data['count'] = $count;
        $data['data'] = $list;
        $this->ajaxReturn($data,'json');
    }

    public function searchinfo(){
        $condi=$_GET;
        $tradetype=intval($_GET['tradetype']);
        $limit = (int)10;
        $p=empty($_GET['p'])?1:$_GET['p'];
        $skip=($p-1)*$limit;

        $where = ' 1=1 ';
        if($tradetype){
            if($tradetype>0){
                $where .= ' and JSON_EXTRACT(log, "$.tradetype") = '.$tradetype;
            }else{
                $ids="(1,2,5,6)";
                $where .= ' and JSON_EXTRACT(log, "$.tradetype")  in  '.$ids;
            }
        }else{
            $condi['tradetype']=6;
            $where .= ' and JSON_EXTRACT(log, "$.tradetype") =6 ';
        }

        if($condi['start_time']){
            $where .= ' and time_virtual>= "'.$condi['start_time'].' 00:00:00"';
        }
        if($condi['end_time']){
            $where .= ' and time_virtual<= "'.$condi['end_time'].' 23:59:59"';
        }

        if($condi['user']){
            $where .= ' and JSON_EXTRACT(log, "$.user_gameid") = '.(int)$condi['user'];
            $idss= "(5,6)";
            $wheres = '   JSON_EXTRACT(log, "$.user_gameid") =  '.(int)$condi['user'].' and JSON_EXTRACT(log, "$.tradetype")  in  '.$idss;
        }
        $lists=$this->gamelog("SELECT log from game_bank where $where order by time_virtual desc limit $skip,$limit");

        $results=$this->gamelog("SELECT id from game_bank where $where order by time_virtual desc");
        $show = $this->page_show(count($results),$limit,$p);
        $alllists=$this->gamelog("SELECT log from game_bank where $wheres");
        foreach ($alllists as $k=> $vo){
            $jsons=get_object_vars(json_decode($vo['log']));
            if($jsons['target_gameid']>0){
                if($jsons['tradegold']>0){  //转入
                    $AInsum +=$jsons['tradegold'];
                }else{ //转出
                    $AOutsum -=$jsons['tradegold'];
                }
            }
        }


        $gameidS= (int)($condi['user']);
        $r=$this->game("SELECT card_no FROM  web_gamecard WHERE  user_game_id = $gameidS and acard_type=1 order by user_use_time desc");  ///充值卡
        $rs=$this->game("SELECT card_no FROM  web_gamecard WHERE  user_game_id = $gameidS and acard_type=0 order by user_use_time desc");  ///新手卡
        $i=0;
        $a=0;
        foreach ($lists as $vo){
            $json=get_object_vars(json_decode($vo['log']));
            if($json['tradetype']==5 ){   //5转入
                $result[$i]['target_bankgold']= $json['user_bankgold'];
                $result[$i]['target_carrygold']=$json['user_carrygold'];
                $result[$i]['target_gameid']=$json['user_gameid'];

                //11月30日新修改 $json['user_nickname'] 截断有“u0000”字符的昵称
                $struser1 = $json['user_nickname'];
                $struser = substr($struser1,strlen($struser1)-5,strlen($struser1));
                if($struser =="u0000"){
                    $struser1 = substr($struser1,0,strlen($struser1)-5);
                }

                $result[$i]['target_nickname']=$struser1;
                $result[$i]['tax']=$json['tax'];
                $result[$i]['tradegold']=$json['tradegold'];
                $result[$i]['tradetype']=$this->getTradetypeName($json['tradetype']);
                $result[$i]['user_bankgold']=$json['target_bankgold'];
                $result[$i]['user_carrygold']=$json['target_carrygold'];
                $result[$i]['user_gameid']=$json['target_gameid'];
                $result[$i]['user_ip']=$json['user_ip'];

                //11月30日新修改 $json['target_nickname'] 截断有“u0000”字符的昵称
                $str = $json['target_nickname'];
                $str2 = substr($str,strlen($str)-5,strlen($str));
                if($str2 =="u0000"){
                    $str = substr($str,0,strlen($str)-5);
                }

                $result[$i]['user_nickname']=$str;
                $result[$i]['time']=$json['time'];
            }else if($json['tradetype']==6){   //转出
                $result[$i]['target_bankgold']= $json['target_bankgold'];
                $result[$i]['target_carrygold']=$json['target_carrygold'];
                $result[$i]['target_gameid']=$json['target_gameid'];

                //11月30日新修改 $json['target_nickname'] 截断有“u0000”字符的昵称
                $str = $json['target_nickname'];
                $str2 = substr($str,strlen($str)-5,strlen($str));
                if($str2 =="u0000"){
                    $str = substr($str,0,strlen($str)-5);
                }

                $result[$i]['target_nickname']=$str;
                $result[$i]['tax']=$json['tax'];
                $result[$i]['tradegold']=$json['tradegold'];
                $result[$i]['tradetype']=$this->getTradetypeName($json['tradetype']);
                $result[$i]['user_bankgold']=$json['user_bankgold'];
                $result[$i]['user_carrygold']=$json['user_carrygold'];
                $result[$i]['user_gameid']=$json['user_gameid'];
                $result[$i]['user_ip']=$json['user_ip'];

                //11月30日新修改 $json['user_nickname'] 截断有“u0000”字符的昵称
                $struser1 = $json['user_nickname'];
                $struser = substr($struser1,strlen($struser1)-5,strlen($struser1));
                if($struser =="u0000"){
                    $struser1 = substr($struser1,0,strlen($struser1)-5);
                }

                $result[$i]['user_nickname']=$struser1;
                $result[$i]['time']=$json['time'];
            }else if($json['tradetype']==2){//充值卡

                $result[$i]['target_bankgold']= $json['user_bankgold'];
                $result[$i]['target_carrygold']=$json['user_carrygold'];
                $result[$i]['target_gameid']=$json['user_gameid'];

                //11月30日新修改 $json['user_nickname'] 截断有“u0000”字符的昵称
                $struser1 = $json['user_nickname'];
                $struser = substr($struser1,strlen($struser1)-5,strlen($struser1));
                if($struser =="u0000"){
                    $struser1 = substr($struser1,0,strlen($struser1)-5);
                }

                $result[$i]['target_nickname']=$struser1;
                $result[$i]['tax']=$json['tax'];
                $result[$i]['tradegold']=$json['tradegold'];
                $result[$i]['tradetype']=$this->getTradetypeName($json['tradetype']);
                $result[$i]['user_bankgold']=$json['target_bankgold'];
                $result[$i]['user_carrygold']=$json['target_carrygold'];
                $result[$i]['user_gameid']=$json['target_gameid'];
                $result[$i]['user_ip']=$json['user_ip'];
                $result[$i]['time']=$json['time'];
                $result[$i]['user_nickname']=$r[$a]['card_no'];
                $a++;
            }else if($json['tradetype']==1){ ///新手卡
                //2018-12-3修复新手卡不能显示的问题
                $result[$i]['target_bankgold']= $json['user_bankgold'];
                $result[$i]['target_carrygold']=$json['user_carrygold'];
                $result[$i]['target_gameid']=$json['user_gameid'];

                //11月30日新修改 $json['user_nickname'] 截断有“u0000”字符的昵称
                $struser1 = $json['user_nickname'];
                $struser = substr($struser1,strlen($struser1)-5,strlen($struser1));
                if($struser =="u0000"){
                    $struser1 = substr($struser1,0,strlen($struser1)-5);
                }

                $result[$i]['target_nickname']=$struser1;
                $result[$i]['tax']=$json['tax'];
                $result[$i]['tradegold']=$json['tradegold'];
                $result[$i]['tradetype']=$this->getTradetypeName($json['tradetype']);
                $result[$i]['user_bankgold']=$json['target_bankgold'];
                $result[$i]['user_carrygold']=$json['target_carrygold'];
                $result[$i]['user_gameid']=$json['target_gameid'];
                $result[$i]['user_ip']=$json['user_ip'];
                $result[$i]['time']=$json['time'];
                $result[$i]['user_nickname']=$rs[0]['card_no'];
            }


            if($json['target_gameid']>0){
                if($json['tradegold']>0){  //转入
                    $Insum +=$json['tradegold'];
                }else{ //转出
                    $Outsum -=$json['tradegold'];
                }
            }
            $i++;
        }

        $shows=$show;
        $pg=array_pop($shows);
        $condi['tradetype_name']=$this->getTradetypeName($condi['tradetype']);
        if($condi['end_time'] && $condi['start_time']){
            $t=$condi['start_time'].'--'.$condi['end_time'].'--'.$condi['tradetype_name'];
        }else if($condi['start_time']){
            $t=$condi['start_time'].'--'.$condi['tradetype_name'];
        }else if($condi['end_time']){
            $t=$condi['end_time'].'--'.$condi['tradetype_name'];
        }else{
            $t=$condi['tradetype_name'];
        }
        $r=$this->actionLog((int)($condi['user']),'查询了gameid为','用户的充值信息',$t);

        /*  echo '<pre>';
          print_r($result);
          echo '</pre>';*/

        $this->assign("totalPages",$pg);
        $this->assign("AInsum",$AInsum);
        $this->assign("AOutsum",$AOutsum);
        $this->assign("Insum",$Insum);
        $this->assign("Outsum",$Outsum);
        $this->assign("p",$p);
        $this->assign("condi",$condi);
        $this->assign("lists",$result);
        // $this->assign("page_show",$show); //分页按钮
        $this->assign("count",count($results));
    }


    /*
     * search
     * 搜索列表
     */
    public function search(){
        $this->display();

    }


    //获取充值信息
    public function getsearch(){
        $useraccount = M('','',$this->con);
        $url = pageurl(__SELF__);
        $pagesize = empty($url['limit'])?10:$url['limit'];
        $page = empty($url['page'])?1:$url['page'];
        $state = ($page-1)*$pagesize;
        $where['orderstatus'] = array('eq','2');
        if(!empty($url['startime']) && !empty($url['endtime'])){
            $where['createtime'] = array('between',array($url['startime'],$url['endtime']));
        }
         if($url['gameid'] > 0 && !empty($url['gameid'])){
                $where['gameid'] = array('eq',$url['gameid']);
         }
          switch ($url['channel']){
                case '-1': //全部
                    /*if($url['gameid'] > 0 && !empty($url['gameid'])){
                        $where['view_gamecard'] = array('eq',$url['gameid']);
                    }*/
                    break;
              case '0'://支付宝
                  $where['channel'] = array('eq','0');
                  break;
                case '1'://微信
                    $where['channel'] = array('eq','1');
                    break;
                case '2'://银行卡
                    $where['channel'] = array('eq','2');
                    break;
              case '3'://代理充值
                  $where['channel'] = array('eq','3');
                  break;
              case '5'://支付宝快充通道
                  $where['outoid'] = array('LIKE','H5P%');
                  break;
              case '6'://支付宝微信定额通道
                  $where['outoid'] = array('LIKE','Jpay%');
                  break;
            }

            $count=$useraccount->table('data_recharge')->where($where)->count();
            $sumprice=$useraccount->table('data_recharge')->field('sum(price) as sumprice')->where($where)->find();
            $sql=$useraccount->table('data_recharge')->fetchSql(true)->field('sum(price) as sumprice')->where($where)->find();
            $list = $useraccount->table('data_recharge')->where($where)->order('createtime desc')->limit($state,$pagesize)->select();

            foreach ($list as $key => $value) {
                if($value['channel'] == '0'){
                    $list[$key]["channelname"] = '支付宝';
                }elseif ($value['channel'] == '1'){
                    $list[$key]["channelname"] = '微信';
                }elseif($value['channel'] == '3'){
                    $list[$key]["channelname"] = '代理充值';
                }else{
                    $list[$key]["channelname"] = '银行卡';
                }
            }

       // $list[0]["sumprice"] = empty($sumprice['sumprice'])?0:$sumprice['sumprice'];
        $r=$this->actionLog((int)(1),'查询了','充值信息');
        $data['code'] = 0;
        $data['message'] = '';
        $data['count'] = $count;
        $data['where'] = $where;
        $data['sql'] = $sql;
        $data['data'] = $list;
        $data['sumprice'] = empty($sumprice['sumprice'])?0:$sumprice['sumprice'];
        $this->ajaxReturn($data,'json');
    }

    public function getname($gmaeid,$filed){
        $useraccount = M('','',$this->con);
        $count=$useraccount->table('data_useraccount')->field($filed)->where('gameid='.$gmaeid)->find();
        return empty($count)?'':$count;
    }

    protected function getTradetypeName($tradetype){
        if($tradetype==1){
            $tradetype_name="新手卡";
        }else if($tradetype==2){
            $tradetype_name="充值卡";
        }else if($tradetype==3){
            $tradetype_name="银行存款";
        }else if($tradetype==4){
            $tradetype_name="银行取款";
        }else if($tradetype==5){
            $tradetype_name="转入";
        }else if($tradetype==6){
            $tradetype_name="转出";
        }else{
            $tradetype_name="全部";
        }
        return $tradetype_name;
    }


}